import os
from moviepy import *
from glob import glob
import re
import subprocess


def merge_audio_and_add_to_video(video_path, audio_base_dir, output_path):
    """
    合并多个音频文件并添加到视频中。

    :param video_path: 视频文件的路径。
    :param audio_base_dir: 包含音频文件的目录。
    :param output_path: 输出视频的路径。
    """
    # 加载视频文件
    video_clip = VideoFileClip(video_path)

    # 初始化音频列表
    audio_clips = []

    # 添加初始静音
    silent_audio_start = AudioClip(lambda t: [0, 0], duration=2)
    audio_clips.append(silent_audio_start)

    # 查找所有的 slide_x.mp3 文件
    mp3_files = sorted(glob(os.path.join(audio_base_dir, "slide_*.mp3")),
                       key=lambda x: int(re.search(r'slide_(\d+)\.mp3', os.path.basename(x)).group(1)))

    # 遍历排序后的mp3文件列表
    for mp3_file in mp3_files:
        # 加载音频文件
        audio_clip = AudioFileClip(mp3_file)

        # 添加到音频列表
        if audio_clips:
            # 在前一个音频之后添加0.3秒的静音
            silent_audio = AudioClip(lambda t: [0, 0], duration=0.3)
            audio_clips.append(silent_audio)
        audio_clips.append(audio_clip)

    # 合并所有音频片段
    final_audio = concatenate_audioclips(audio_clips)

    # 将音频添加到视频中
    video_with_audio = video_clip.with_audio(final_audio)

    # 输出带有新音频的视频文件
    video_with_audio.write_videofile(output_path, codec='libx264', audio_codec='aac')

    # 关闭剪辑对象，释放资源
    video_clip.close()


def merge_video_and_subtitle(video_and_srt_path, base_name):
    video_ext = ".mp4"
    srt_ext = ".srt"

    video_path = os.path.join(video_and_srt_path, f"{base_name}_with_audio" + video_ext).replace("\\", "/")
    srt_path = os.path.join(video_and_srt_path, base_name + srt_ext).replace("\\", "/")
    output_path = os.path.join(video_and_srt_path, f"{base_name}_with_audio_with_subs" + video_ext).replace("\\", "/")

    command = [
        'ffmpeg',
        '-i', video_path,
        '-vf', f'subtitles={srt_path}',
        '-c:a', 'copy',
        output_path
    ]

    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError as e:
        print(f"An error occurred while merging video and subtitles: {e}")